<?php
namespace app\api\business;

use app\lib\Arr;
use app\model\mysql\ProductSku;
use app\model\mysql\ProductSpecValue;
use think\Exception;
use app\business\Category;
use think\facade\Log;

class Product {

    protected $model;
    protected $skuModel;
    protected $specValueModel;

    public function __construct() {

        $this->model = new \app\model\mysql\Product();
        $this->skuModel = new ProductSku();
        $this->specValueModel = new ProductSpecValue();
    }

    public function categoryGoodsRecommend($pageSize = 6, $fields = "") : array {

        try{
            $products =  $this->model->recommendGoods($pageSize, $fields);

            $cBunis = new Category();
            $categoryIds = [];
            foreach ($products as $product) {
                $categoryPath = $product["category_path_id"];
                $categoryPathArr = explode(",", $categoryPath);
                $categoryIds = array_merge($categoryIds, $categoryPathArr);
            }
            $categories = $cBunis->list(0, "id, pid, name", [
                ["id", "in", $categoryIds]
            ]);
            $categories = Arr::getTree($categories);
            $result = [];

            foreach ($categories as $key => $category) {
                $result[$key]["categorys"] = [
                    "id" => $category["id"],
                    "name" => $category["name"],
                    "list" => $category["list"]
                ];
                foreach ($products as $product) {
                    $categoryPath = $product["category_path_id"];
                    $categoryPathArr = explode(",", $categoryPath);
                    if (in_array($category["id"], $categoryPathArr)){
                        $result[$key]["goods"][] = [
                            "id" => $product["id"],
                            "image" => $product["recommend_img"],
                            "price" => $product["price"],
                            "title" => $product["title"],
                            "sku_id" => $product["sku_id"]
                        ];
                    }
                }
            }

            unset($categories, $products);
            return $result;

        }catch (Exception $e){
            Log::error($e);
            return [];
        }

    }

    public function processSearchParams($params = []) : array {
        $data["order"] = [
            "id" => "DESC",
        ];
        $data["page"] = 1;
        $data["pageSize"] = 10;
        if (isset($params["category_id"]) && $params["category_id"] > 0) {
            $data["FIND_IN_SET"] = ["category_path_id", $params["category_id"]];
        }

        if (isset($params["keyword"]) && !empty($params["keyword"])) {
            $data["where"][] = ["title", "like", "%". $params["keyword"] . "%"];
        }

        if (isset($params["page"]) && $params["page"] > 1) {
            $data["page"] = $params["page"];
        }

        if (isset($params["page_size"]) && $params["page_size"] > 0) {
            $data["pageSize"] = $params["page_size"];
        }
        if (isset($params["order"]) && !empty($params["order"])) {
            $data["order"] = $params["order"];
        }

        if (isset($params["field"]) && !empty($params["field"])) {
            $data["field"] = $params["field"];
        }

        return $data;
    }

    public function search($params = []) : array {

        $data = $this->processSearchParams($params);

        try{
            return $this->model->search($data);
        }catch (Exception $e){
            Log::error($e);
            return [];
        }

    }

    protected function getSpecSkus($sku = []) : array {
        if (empty($sku)) {
            return [];
        }
        $result = [];
        $skus = $this->skuModel->where("is_delete", 0)
            ->where("product_id", $sku["product_id"])->select();
        $skus = $skus->toArray();
        $specValueIds = [];
        $ids = array_column($skus, "id");
        $specValueIdsArr = array_column($skus, "spec_value_ids");
        $key = array_search(null, $specValueIdsArr);
        unset($specValueIdsArr[$key], $ids[$key]);
        $result["gids"] = array_combine($specValueIdsArr, $ids);

        $specValueIdArr = [];
        foreach ($specValueIdsArr as $value) {
            $specValueIdArr = array_merge($specValueIdArr, explode(",", $value));
        }
        $specValueIdArr = array_unique($specValueIdArr);
        $specValueResult = $this->specValueModel->getListByIds($specValueIdArr);

        $flagIds = explode(",", $sku["spec_value_ids"]);
        $result["sku"] = [];
        foreach ($specValueResult as $value) {
            $list = [
                "id" => $value["id"],
                "name" => $value["name"],
                "flag" => in_array($value["id"], $flagIds) ? 1 : 0
            ];
            if (isset($result["sku"][$value["spec_id"]])){
                $result["sku"][$value["spec_id"]]["list"][] = $list;
            }else {
                $result["sku"][$value["spec_id"]] = [
                    "name" => $value["spec"]["name"],
                    "list" => [$list]
                ];
            }
        }

        return $result;
    }

    public function getSkuWithProduct($id = 0) : array {
        if ($id <= 0) {
            return [];
        }

        $result = $this->skuModel->with("product")->find($id);
        if (!$result) {
            return [];
        }
        return $result->toArray();
    }


    public function detail($id = 0) : array {
        if ($id <= 0) {
            return [];
        }
        try{

            $sku = $this->getSkuWithProduct($id);
            $result = [
                "image" => explode(",", $sku["product"]["carousel_img"]),
                "title" => $sku["product"]["title"],
                "price" => $sku["price"],
                "cost_price" => $sku["cost_price"],
                "sales_count" => 0,
                "stock" => $sku["stock"],
                "detail" => [
                    "d1" => [
                        "商品编号" => $sku["sku"],
                        "上架时间" => "",
                        "商品毛重" => "",
                        "商品编号" => "",
                        "商品库存" => $sku["stock"],
                    ],
                    "d2" => $sku["product"]["description"],
                ]
            ];

            $result = array_merge($result, $this->getSpecSkus($sku));

            return $result;
        }catch (Exception $e){
            Log::error($e);
            return [];
        }

    }
}